package sz.szsmk.citizencard.ui.activity;


import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.chenenyu.router.annotation.Route;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.umeng.message.PushAgent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import kr.co.namee.permissiongen.PermissionGen;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.ActivityMainBinding;
import sz.szsmk.citizencard.dialog.LifeAuthorizationDialog;
import sz.szsmk.citizencard.dialog.OneButtonDialog;
import sz.szsmk.citizencard.dialog.SuccessDialog;
import sz.szsmk.citizencard.dialog.TwoUpDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.DownloadUtils;
import sz.szsmk.citizencard.model.network.bean.JumpActivityBean;
import sz.szsmk.citizencard.model.network.bean.JumpActivityEventBusBean;
import sz.szsmk.citizencard.model.network.bean.response.CheckIsChargeRes;
import sz.szsmk.citizencard.model.network.bean.response.GetCodeResponse;
import sz.szsmk.citizencard.model.network.bean.response.GetOrderOpenidRes;
import sz.szsmk.citizencard.model.network.bean.response.ProtocolsRes;
import sz.szsmk.citizencard.model.network.bean.response.ProtocolsShowRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryCitizenCardRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserCardRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserCardResponse;
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes;
import sz.szsmk.citizencard.model.network.bean.response.UpdataVersionRes;
import sz.szsmk.citizencard.model.network.bean.response.UserInfoRes;
import sz.szsmk.citizencard.model.network.bean.response.VerifyBindNgUserRes;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThirdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealNameRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetOpenIdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.model.network.dzbean.res.QueryDzsmkAgreeMentRes;
import sz.szsmk.citizencard.mvp.contract.IMainContact;
import sz.szsmk.citizencard.mvp.presenter.IMainPresenter;
import sz.szsmk.citizencard.receiver.LocationReceiver;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.ui.dialogs.PolicyDialog;
import sz.szsmk.citizencard.ui.dialogs.ProtocolDialog;
import sz.szsmk.citizencard.ui.dialogs.WalletAuthDialogNew;
import sz.szsmk.citizencard.ui.fragment.ElecCardSignDialog;
import sz.szsmk.citizencard.ui.fragment.GoverFragment;
import sz.szsmk.citizencard.ui.newversion.bean.TabEntity;
import sz.szsmk.citizencard.ui.newversion.config.Constants;
import sz.szsmk.citizencard.ui.newversion.fragment.MeFragment;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PermissionUtil;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.util.SecureSharedPreferences;
import sz.szsmk.citizencard.util.StringUtils;

import static sz.szsmk.citizencard.util.Constant.SZ_URL;


@Route("main")
public class IMainActivity extends IBaseActivity<IMainPresenter, ActivityMainBinding>
        implements IMainContact.IMainView, View.OnClickListener {

    private long miExitTime = 0;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private String currentOperation = "";
    /**
     * 权限码
     */
    private String versionName;
    private static final int PERMISS_CODE = 0X11;

    public LocationClient mLocationClient = null;
    private String openId;
    private String access_token;


    private String[] mTitles = {"首页",  "生活","服务", "我的"};
    private int[] mIconUnselectIds = {
            R.mipmap.icon_home_normal, R.mipmap.icon_life_normal,
            R.mipmap.icon_service_normal, R.mipmap.icon_me_normal};
    private int[] mIconSelectIds = {
            R.mipmap.icon_home, R.mipmap.icon_life,
            R.mipmap.icon_service, R.mipmap.icon_me};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private Bundle userBundle;

    private PushAgent mPushAgent;
    private Handler umHandler;

    //    不可以随意改动
    private static BDLocation currentLocation;

    public static void setCurrentLocation(BDLocation currentLocation) {
        IMainActivity.currentLocation = currentLocation;
    }

    public static BDLocation getCurrentLocation() {
        if (currentLocation != null)
            return currentLocation;
        else {

            BDLocation location = new BDLocation();
            location.setLatitude(31.30003156904d);
            location.setLongitude(120.5788896605d);
            location.setAddrStr("苏州市");
            setCurrentLocation(location);
            return location;
        }
    }


    //高德    固定坐标 苏州
    private LatLng appLocation;

    public LatLng getAppLocation() {
        if(appLocation==null){
            appLocation = new  LatLng(120.585257,31.299824);
        }
        return appLocation;
    }

    public void setAppLocation(LatLng appLocation) {
        this.appLocation = appLocation;
    }


    @Override
    public void updataError() {

    }

    @Override
    public void updataSuccess(GetCodeResponse loginResponse) {

    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent()).build().inject(this);
    }

    @Override
    protected void initViews() {

//        String url1 = "http://192.168.101.120:8901/app-front-end/#/payFail?orderId=3740567&tradeType=2&access_token="+ACache.get(this).getAsString("access_token");;
//        Bundle bundle = new Bundle();
//        bundle.putString("url", url1);
//        JumpUtils.jumptoNatvie(this, "webView", 0, bundle);

//        JumpUtils.jumptoNatvie(this, "payCodeCheck", 0, null);

        initFragment();
        access_token = ACache.get(this).getAsString("access_token");
        if (access_token != null) {
            mPresenter.addPush(access_token);
        }

        PackageManager packageManager = getPackageManager();
        String packageName = getPackageName();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        mPresenter.checkVersion(versionName);
        mPresenter.getGestureIsOpen(this);


        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(new LocationReceiver());
        //注册监听函数
        initLocation();
        requestLocation();
//        List<String> permissionList = new ArrayList<>();
//        if (ContextCompat.checkSelfPermission(IMainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
//        }
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//            permissionList.add(Manifest.permission.READ_PHONE_STATE);
//        }
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//        }
//
//        if (!permissionList.isEmpty()) {
//            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
//            ActivityCompat.requestPermissions(IMainActivity.this, permissions, 1);
//        } else {
//
//        }

        webToNatvie(getIntent());
        //初始化底部导航
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }


        dataBinding.myTab.ctlBottomNav.setTabData(mTabEntities);
        dataBinding.myTab.ctlBottomNav.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.content_panel, mFragments.get(position)).commitAllowingStateLoss();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_panel, mFragments.get(0)).commitAllowingStateLoss();



    }



    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        webToNatvie(intent);
    }


    private void webToNatvie(Intent intent) {
        Bundle bundle = null;
        if (intent.getData() != null) {
            bundle = new Bundle();
            Uri uri = intent.getData();
            if (uri != null) {
                try {
                    JumpActivityBean jumpActivityBean = new Gson().fromJson(uri.getQueryParameter("data"), JumpActivityBean.class);
                    bundle.putSerializable("jumpActivityBean", jumpActivityBean);
                    if (access_token != null) {
                        JumpUtils.jumptoNatvie(this,
                                jumpActivityBean.getActivity(), 0, jumpActivityBean.getBundles());
                    } else {
                        if (!AndroidUtils.isTopActivity("LoginActivity", IMainActivity.this)) {
                            JumpUtils.jump(this, "login", 0);
                        }
                    }
                } catch (Exception e) {

                }
            }
        }
        String nfc = getIntent().getStringExtra("nfc");
        if (!"nodata".equals(nfc)) {
            bundle = new Bundle();
            if (access_token != null) {
            } else {
                JumpUtils.jump(this, "login", 0);
            }
        }
    }

    private void requestLocation() {
        mLocationClient.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mLocationClient.stop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getPersonInfomation("test");
        mPresenter.sendMainRequest();
        access_token = ACache.get(this).getAsString("access_token");
        if (access_token != null) {
            mPresenter.addPush(access_token);
            //这里 请求 结果 都是 静态变量
            mPresenter.getConfig();
            mPresenter.getAuthType();
            mPresenter.getGetOrderIdForGHF();   //获取桂花分 拼接参数
            if (StringUtils.isEmpty(ACache.get(DaggerApplication.getIns()).getAsString("protocolVersion"))) {
                mPresenter.getProtocols("zhsz_app_zhuce");//查询协议
            }
        }

    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");

        option.setOpenGps(true);
        option.setScanSpan(8 * 1000);
        option.setIsNeedAddress(true);
        option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
//        option.setWifiCacheTimeOut(5*60*1000);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
    }

    private void initFragment() {

        //首页
        mFragments.add(sz.szsmk.citizencard.ui.newversion.fragment.HomeFragment.Companion.getInstance());

        //生活
        mFragments.add(sz.szsmk.citizencard.ui.newversion.fragment.LifeFragment.Companion.getInstance());
        //服务
        mFragments.add(GoverFragment.getInstance());


        //我的
        mFragments.add(MeFragment.Companion.getInstance());


    }

    @Override
    protected void updateViews() {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //权限弹框提示
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            PermissionUtil.checkPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE,getResources().getString(R.string.write_permission));
        }

        //关怀模式
        if (SecureSharedPreferences.getBoolean("pilicyDialog",true)){
            PolicyDialog policyDialog = new PolicyDialog(this);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                policyDialog.showDialog(this);
            }
        }

        //requestSctSdkPermiss();
        EventBus.getDefault().register(this);
        //判断是否开启了关怀模式
        if (SecureSharedPreferences.getBoolean("careMode",false)){
            Log.e("careMode",SecureSharedPreferences.getBoolean("careMode", false)+"");
            Intent intent = new Intent(this,CareModeActivity.class);
            startActivityForResult(intent,3003);
        }

    }



    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - miExitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            miExitTime = System.currentTimeMillis();
        } else {
            //清除栈内数据
            this.finish();
            System.exit(0);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /***
     * 去设置界面
     */
    public static void goToSetting(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        context.startActivity(intent);
    }

    private MessageEvent mEvent;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getCode() == MessageEvent.CODE_GESTURE_OPEN) {
            mPresenter.getGestureIsOpen(this);
        } else if (event.getCode() == MessageEvent.TO_DZSMK) {
            showLoadingDialog();
            mPresenter.getOpenId();
        } else if (event.getCode() == MessageEvent.TO_GOVER) {
            if (access_token != null) {
                Bundle bundle = new Bundle();
                bundle.putString("data", "changeAll");
                mFragments.get(2).setArguments(bundle);
                dataBinding.myTab.ctlBottomNav.setCurrentTab(2);
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.content_panel, mFragments.get(2)).commitAllowingStateLoss();
                EventBus.getDefault().post(new MessageEvent(MessageEvent.CODE_EDIT_ALL));
            } else {
                JumpUtils.jump(this, "login", 0);
            }
        } else if (event.getCode() == MessageEvent.CODE_USERBEHAVIOR) {
            //埋点
            mPresenter.userBehaviorBrowse((Integer) event.getData());
        } else if (event.getCode() == MessageEvent.CODE_OPENNG) {
            //event 中 data 有数据 表示 直接跳转有数据url
            if (ACache.get(this).getAsString("access_token") != null) {
                //NG 授权开始
                //------>step1 获取协议  ---->step2 查询是否显示   --->step3 不显示 则原流程继续  显示 则显示 只有在确定之后继续原流程
                currentOperation = "finance";  //标记当前操作是什么
                mPresenter.getProtocols("shmjr_shq");
                mEvent = event;
//                mPresenter.verifyBindNgUser(event.getData());
            } else {
                JumpUtils.jump(this, "login", 0);
            }
        }else if(event.getCode() == MessageEvent.CODE_WALLET){
            //event 中 data 有数据 表示 直接跳转有数据url
            if (ACache.get(this).getAsString("access_token") != null) {
                //钱包 授权开始
                //查询协议 并显示弹窗  获取钱包协议
                currentOperation = "wallet";
                mPresenter.getProtocols("hmqb_shq");
                mEvent = event;
//                mPresenter.verifybindWalletuser(event.getData());
            } else {
                JumpUtils.jump(this, "login", 0);
            }
        } else if (event.getCode() == MessageEvent.CODE_TOKEN_ERROR) {
            //token异常  在其他终端登录
            ACache.get(DaggerApplication.getIns()).remove("login_type");
            //TokenErrorDialog.Companion.show(this);
        } else if(event.getCode() == MessageEvent.CODE_GJJ_GHF_SB ){
            if(ACache.get(this).getAsString("access_token") !=null){
                //首页 统一跳转 桂花分 公积金 社保
                mPresenter.selectUserAuth(event.getData().toString());
            }else{
                JumpUtils.jump(this, "login", 0);
            }
        }else if(event.getCode() == MessageEvent.CODE_JUMP_DZSMK ){
            //跳转电子市民卡
            showLoadingDialog();
            mPresenter.queryUserCard("", "3");
//            mPresenter.queryCitizenCard();
        }else if(event.getCode() == MessageEvent.CODE_LIFEAUTH ){
            if(ACache.get(this).getAsString("access_token") !=null){
                mPresenter.verifyBindNgUser(event.getData());
            }else{
                JumpUtils.jump(this, "login", 0);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(JumpActivityEventBusBean event) {
        switch (event.getCode()){
            case MessageEvent.CODE_OPENNG:
                if(ACache.get(this).getAsString("access_token") !=null){
                    //NG 授权开始
                    mPresenter.verifyBindNgUser(event.getBundles().getString("link_url"));
                }else{
                    JumpUtils.jump(this, "login", 0);
                }
                break;

        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }


    /**
     * 获取presenter
     *
     * @return
     */
    public IMainPresenter getmPresenter() {
        return mPresenter;
    }

    private void gotoActivity(String url) {
        Intent intent = new Intent(this, YouzanActivity.class);
        intent.putExtra(YouzanActivity.KEY_URL, url);
        startActivity(intent);
    }

    @Override
    public void checkIsOpenElecCardSuccess(CheckIsRealNameRes loginResponse) {
        dismissLoadingDialog();
        //4.已实名，判断是否已首冲  未实名 弹窗去实名
        if (loginResponse != null) {
            String isRealName = loginResponse.getData().getIsRealName();
            if (isRealName.equals("0")) {

                ACache.get(DaggerApplication.getIns()).put("channelId", "000001");
                mPresenter.preAuthThird(openId, "1");

            } else if (isRealName.equals("1")) {
                mPresenter.queryDzsmkAgreement(openId);
            }
        }
    }

    @Override
    protected void initSystemBar() {
        ImmersionBar.with(this).init();
    }

    @Override
    public void checkIsOpenElecCardError(CheckIsRealNameRes preAuthRes) {
        dismissLoadingDialog();
    }

    @Override
    public void checkIsChargeFail() {
        dismissLoadingDialog();
    }

    @Override
    public void checkIsChargeSucc(CheckIsChargeRes ibaseBean) {
        dismissLoadingDialog();
        String code = ibaseBean.getCode();
//        mPresenter.preAuthThird(openId, openId);
        if (code.equals("0000")) {
            String isReCharge = ibaseBean.getData().getIsReCharge();
            if (isReCharge.equals("1")) {

                JumpUtils.jumptoNatvie(this, Constants.SCANQRCODECHECKACTIVITY, 0, null);

            } else if (isReCharge.equals("0")) {
                ElecCardSignDialog dialog = new ElecCardSignDialog();
                dialog.setAction(1);
                dialog.show(this.getFragmentManager(), null);
            }
        } else {
            final SuccessDialog dialog = new SuccessDialog(this, ibaseBean.getMessage());
            dialog.show();
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    dialog.cancel();
                }
            }.start();
        }
    }

    @Override
    public void queryDzsmkAgreementFail(QueryDzsmkAgreeMentRes response) {
        if (response.getCode().equals("000005")) {
            mPresenter.preAuthThird(openId, "2");
            dismissLoadingDialog();
        } else {
            PubUtils.popTipOrWarn(this, response.getMessage());
            dismissLoadingDialog();
        }
    }

    @Override
    public void queryDzsmkAgreementSucc() {
        dismissLoadingDialog();
    }

    @Override
    public void getOpenIdSucc(GetOpenIdRes response) {
        dismissLoadingDialog();
        openId = ACache.get(this).getAsString("openId");
        mPresenter.checkIsOpenElecCard(openId);
    }

    @Override
    public void getOpenIdFail(GetOpenIdRes response) {
        PubUtils.popTipOrWarn(DaggerApplication.getIns(), response.getMessage());
        dismissLoadingDialog();
    }

    @Override
    public void addPushSucc() {

    }

    @Override
    public void addPushFail() {

    }
    TwoUpDialog dialog;
    String downloadAPKPath;
    @Override
    public void checkVersionSucc(final UpdataVersionRes response) {
        downloadAPKPath = this.getCacheDir().toString()+"/apkCache/zhsz.apk";
        int status = response.getStatus();
        if (status == 0) {
//            Toast.makeText(this, "不需要更新版本", Toast.LENGTH_SHORT).show();
            File file = new File(downloadAPKPath);
            //清除之前更新内容
            if(file.exists()){
                file.delete();
            }
        } else if (status == 1) {
            dialog = new TwoUpDialog(this, response.getImgUrl());
            dialog.setCancelable(false);
            dialog.setOnKeyListener(keylistener);
            dialog.setOnCanClickListener(new TwoUpDialog.OnCanClickListener() {
                @Override
                public void onCanClick() {
                    dialog.cancel();
                    dialog.dismiss();
                }
            });
            dialog.setOnOkClickListener(new TwoUpDialog.OnOkClickListener() {
                @Override
                public void onOkClick() {
                    if (!android.os.Environment.getExternalStorageState().equals(
                            android.os.Environment.MEDIA_MOUNTED)) {
                        PubUtils.popTipOrWarn(IMainActivity.this, "SD卡不存在！");
                    } else {
                        // 弹出下载框
                        String url = response.getDownloadUrl();
                        L.e(Constant.TAG, "下载的地址连接：" + url);
                        showDownloadDialog(response.getDownloadUrl());
//                        showDownloadDialog("https://newapp.szsmk.com/images/msgpush/app-release.apk");
                    }
                    dialog.cancel();
                }
            });
            dialog.show();

        } else if (status == 2) {
            final OneButtonDialog dialog = new OneButtonDialog(this, response.getImgUrl());
            dialog.setCancelable(false);
            dialog.setOnKeyListener(keylistener);
            dialog.setOnOkClickListener(new OneButtonDialog.OnOkClickListener() {
                @Override
                public void onOkClick() {
                    if (!android.os.Environment.getExternalStorageState().equals(
                            android.os.Environment.MEDIA_MOUNTED)) {
                        PubUtils.popTipOrWarn(IMainActivity.this, "SD卡不存在！");
                    } else {
                        // 弹出下载框
                        String url = response.getDownloadUrl();
                        L.e(Constant.TAG, "下载的地址连接：" + url);
                        showDownloadDialog(response.getDownloadUrl());
//                        showDownloadDialog("https://newapp.szsmk.com/images/msgpush/app-release.apk");
                    }
                }
            });
            dialog.show();
        }
    }

    private ProgressBar progressBar;
    private AlertDialog mDialog;

    /**
     * 弹出下载框
     */
    public void showDownloadDialog(final String downloadUrl) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                PubUtils.popTipOrWarn(IMainActivity.this, "未获取到读写文件的权限！");
                return;
            }
        }

        if (TextUtils.isEmpty(downloadUrl))
            return;
        if (DownloadUtils.hasDownloadLatest(IMainActivity.this, downloadUrl)) {
            //已下载最新的Apk，则直接安装
//            DownloadUtils.installApk(IMainActivity.this, downloadUrl);
//            删除本地包重新下载
            DownloadUtils.deleteFile(IMainActivity.this, downloadUrl);
        }

        FileDownloader.setup(this);
        FileDownloader.getImpl().create(downloadUrl).
                setPath(downloadAPKPath).
                setListener(new FileDownloadListener(){
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        if (totalBytes > 0) {
                            // 更新进度情况
                            int progress = (int) ((Float.valueOf(soFarBytes)/Float.valueOf(totalBytes)) * 100f);
                            progressBar.setProgress(progress);
                        } else {
                            progressBar.setIndeterminate(true);
                        }
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        progressBar.setVisibility(View.INVISIBLE);
                        mDialog.dismiss();
                        // 安装apk文件

                        installApk(new File(task.getPath()));

                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        PubUtils.popTipOrWarn(IMainActivity.this, "下载失败");
                        mDialog.dismiss();
                        DownloadUtils.deleteApk(IMainActivity.this);
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {

                    }
                }).start();

        AlertDialog.Builder builder = new AlertDialog.Builder(IMainActivity.this);
        builder.setTitle("版本更新中...");
        builder.setOnKeyListener(keylistener);
        builder.setCancelable(false);
        final LayoutInflater IF = LayoutInflater.from(IMainActivity.this);
        View v = IF.inflate(R.layout.update_prgress, null);
        progressBar = (ProgressBar) v.findViewById(R.id.pb_update_progress);
        builder.setView(v);
        mDialog = builder.create();
        mDialog.setCancelable(false);
        mDialog.show();
    }

    private void installApk(File apkFile ) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this,
                    this.getPackageName() + ".fileProvider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(
                    Uri.fromFile(new File(apkFile.getAbsolutePath())),
                    "application/vnd.android.package-archive");
        }

        startActivityForResult(intent, 0x666);
    }

    public void queryCard(String sign) {
        Constant.isBind = false;
        if (sign.equals("home")) {
            Constant.isBind = true;
        }
        showLoadingDialog();
        mPresenter.queryUserCard("", "3");
    }

    public void queryUserCard(String sign) {
        Constant.isBind = false;
        if (sign.equals("home") || sign.equals("gover")) {
            Constant.isBind = true;
        }
        showLoadingDialog();
        mPresenter.queryUserCard("", "3");
    }

    /**
     * 不可以返回
     */
    DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                return true;
            } else {
                return false;
            }
        }
    };

    /**
     * 声明一个handler来跟进进度条
     */
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    progressBar.setIndeterminate(true);
                    break;
                case 1:
                    // 更新进度情况
                    long[] obj = (long[]) msg.obj;
                    int progress = (int) (((float) obj[0] / obj[1]) * 100);
                    progressBar.setProgress(progress);
                    break;
                case 0:
                    progressBar.setVisibility(View.INVISIBLE);
                    finish();
                    // 安装apk文件
                    DownloadUtils.installApk(IMainActivity.this, (String) msg.obj);
                    break;
                case 3:
                    PubUtils.popTipOrWarn(IMainActivity.this, "下载失败");
                    finish();
                    DownloadUtils.deleteApk(IMainActivity.this);
                    mDialog.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 启动到应用商店app详情界面
     *
     * @param appPkg    目标App的包名
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public void launchAppDetail(String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) return;

            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 失败了就删除apk包，下次进入重新下载
         */
        if (requestCode == 0x666) {
            if (resultCode == RESULT_CANCELED || resultCode == RESULT_FIRST_USER) {
                DownloadUtils.deleteApk(IMainActivity.this);
            }
            finish();
        }
        if (resultCode == RESULT_OK){
        }

        if(requestCode==3003&&resultCode==3004){
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.content_panel,mFragments.get(2));
            dataBinding.myTab.ctlBottomNav.setCurrentTab(2);
            transaction.commit();
        }
    }

    @Override
    public void checkVersionFail() {

    }


    @Override
    public void mainPageFail() {

    }

    @Override
    public void preAuthThirdSucc(String id) {
        if (id.equals("2")) {
            mPresenter.checkIsCharge();
        } else {
            JumpUtils.jump(this, Constants.SCANQRCODECHECKACTIVITY, 1);
        }
    }

    @Override
    public void preAuthThirdFail(PreAuthThirdRes preAuthRes) {
        //success的时候有首次充值的判断，没有直接略过这个判断逻辑。在失败的时候依旧跳转
//        PubUtils.popTipOrWarn(this, preAuthRes.getMessage());
        JumpUtils.jump(this, Constants.SCANQRCODECHECKACTIVITY, 1);
    }

    @Override
    public void recordUserFunctionSucc() {

    }

    @Override
    public void recordUserFunctionFail() {

    }

    @Override
    public void getAuthTypeFail() {

    }

    @Override
    public void getAuthTypeSucc() {

    }

    @Override
    public void getGetOrderIdFail() {

    }

    @Override
    public void getGetOrderIdSucc(GetOrderOpenidRes response, String url, String type) {

    }

    @Override
    public void queryCitizenCardSucc(QueryCitizenCardRes response) {
        dismissLoadingDialog();
        if (response.getCitizenCardInfoList() == null || response.getCitizenCardInfoList().size() == 0) {
            Bundle bundle = new Bundle();
            bundle.putString("key", "home");
            JumpUtils.jumptoNatvie(this, "addnewcard", 0, bundle);
        } else {
            Intent intent = new Intent(this, CitizenCardActivity.class);
            intent.putExtra("type", "3");
            intent.putExtra("citizenCardData", response);
            startActivity(intent);

        }
    }

    @Override
    public void queryCitizenCardFail(QueryCitizenCardRes response) {

    }

    @Override
    public void queryUserCardSuccess(QueryUserCardRes response) {
        dismissLoadingDialog();
        if (response.getData() == null || response.getData().size() == 0) {
            Bundle bundle = new Bundle();
            bundle.putString("key", "home");
            JumpUtils.jumptoNatvie(this, "addnewcard", 0, bundle);
        } else {
            Intent intent = new Intent(this, CitizenCardActivity.class);
            intent.putExtra("type", "3");
            intent.putExtra("citizenCardData", response);
            startActivity(intent);
        }
//        Bundle bundle = new Bundle();
//        bundle.putString("key", "home");
//        JumpUtils.jumptoNatvie(this, "addnewcard", 0, bundle);
    }

    @Override
    public void queryUserCardSuccess(QueryUserCardResponse response) {
        dismissLoadingDialog();
        if (response.getData() == null || response.getData().size() == 0) {
            Bundle bundle = new Bundle();
            bundle.putString("key", "home");
            JumpUtils.jumptoNatvie(this, "addnewcard", 0, bundle);
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("type", "3");
            bundle.putSerializable("cardList", response);
            JumpUtils.jumptoNatvie(this, "routinecarddetail", 0, bundle);
        }
    }

    @Override
    public void queryUserCardFalie(String msg) {

    }

    @Override
    public void verifyBindNgUserSucc(VerifyBindNgUserRes verifyBindNgUserRes, Object ng_url) {
        //是否授权
        if (verifyBindNgUserRes.isHasBindNgUser()) {
            Bundle bundle = new Bundle();
            String nGaccess_token = verifyBindNgUserRes.getNgAccessToken();

            String urlparam;
            if(ng_url.toString().contains("?")){
                urlparam =  "&";
            }else{
                urlparam =  "?";
            }
            urlparam += "token="+ nGaccess_token +"&access_token=" + nGaccess_token;
            bundle.putString("url",ng_url + urlparam)  ;

            JumpUtils.jumptoNatvie(IMainActivity.this, "webView", 0, bundle);
        } else {
            //弹窗 绑定Ng
            LifeAuthorizationDialog dialog = new LifeAuthorizationDialog(new LifeAuthorizationDialog.LifeAuthClick() {
                @Override
                public void onClick() {
                    //绑定
                    mPresenter.toBindNgUser(ng_url);
                }
            });
            dialog.show(getSupportFragmentManager(),"");
        }


    }

    @Override
    public void toBindNgUserSucc(VerifyBindNgUserRes verifyBindNgUserRes, Object ng_url) {
        //绑定成功
        Bundle bundle = new Bundle();
        String nGaccess_token = verifyBindNgUserRes.getNgAccessToken();
        bundle.putString("url", ng_url + nGaccess_token);
        JumpUtils.jumptoNatvie(IMainActivity.this, "webView", 0, bundle);
    }

    @Override
    public void verifybindWalletuserSucc(VerifyBindNgUserRes verifyBindNgUserRes, Object ng_url) {
        //        true: 已经绑定授权过
        if (verifyBindNgUserRes.isHasBindNgUser() == true) {
            Bundle bundle = new Bundle();
            bundle.putString("url",  (ng_url==null? Constant.MyWelletUrl:ng_url.toString() ) +
                    ACache.get(DaggerApplication.getIns()).getAsString("access_token"));
            JumpUtils.jumptoNatvie(IMainActivity.this, "webView", 0, bundle);
        } else {
            mPresenter.toBindWallet(ng_url);
        }
    }

    @Override
    public void toBindWalletUserSucc(VerifyBindNgUserRes verifyBindNgUserRes, Object ng_url) {
        Bundle bundle = new Bundle();
        bundle.putString("url",  (ng_url==null? Constant.MyWelletUrl:ng_url.toString() )+ "&access_token="+
                ACache.get(DaggerApplication.getIns()).getAsString("access_token"));
        JumpUtils.jumptoNatvie(IMainActivity.this, "webView", 0, bundle);
    }

    @Override
    public void selectUserAuthSucc(SeleciUserAuthRes response, String type) {
        //公积金 桂花分 社保 跳转
        String access_token = ACache.get(this).getAsString("access_token");
        List<SeleciUserAuthRes.AuthTypeListBean> authTypeList = response.getAuthTypeList();

        if (type.equals("gjj")) {
            String isAuth = authTypeList.get(1).getIsAuth();
            //0未授权，1已授权，2未实名(L3认证)
            if (isAuth.equals("2")) {
                Bundle bundle = new Bundle();
                bundle.putInt("intotype", 1);
                bundle.putString("choosetype", "gjj");
                JumpUtils.jumptoNatvie(this, "RealNameActivity", 0, bundle);
            } else if (isAuth.equals("1")) {
                Bundle bundle = new Bundle();
                String path = Constant.BASE_URL + "app-front-end/#/fund/main?access_token=" + access_token;
                bundle.putString("url", path);
                bundle.putString(Constant.CUST_NAME, Constant.ID_NAME);
                JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
            } else if (isAuth.equals("0")) {
                String url =Constant.BASE_URL + "app-front-end/#/fund/main?access_token=" + access_token;
                Bundle bundle = new Bundle();
                bundle.putString("url", url);
                JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
            }
        }

        if (type.equals("sb")) {
            String isAuth = authTypeList.get(0).getIsAuth();
            //0未授权，1已授权，2未实名(L3认证)
            if (isAuth.equals("2")) {
                Bundle bundle = new Bundle();
                bundle.putInt("intotype", 1);
                bundle.putString("choosetype", "sb");
                JumpUtils.jumptoNatvie(this, "RealNameActivity", 0, bundle);
            } else if (isAuth.equals("1")) {
                Bundle bundle = new Bundle();
                String path = Constant.BASE_URL + "app-front-end/#/social/main?access_token=" + access_token;
                bundle.putString("url", path);
                JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
            } else if (isAuth.equals("0")) {
                String url = Constant.BASE_URL + "app-front-end/#/fundAndSociety/authPage?access_token=" + access_token + "&type=1&name=" + Constant.ID_NAME;
                Bundle bundle = new Bundle();
                bundle.putString("url", url);
                JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
            }
        }
        if (type.equals("ghf")) {
            String isAuth = authTypeList.get(2).getIsAuth();
            //0未授权 直接跳 他们网页，1已授权，2未实名(L3认证)
            if (isAuth.equals("0")|| isAuth.equals("1")) {

                Bundle bundle = new Bundle();
                //跳转桂花分
                String murl = SZ_URL+"?" + Constant.EXTENT_GHF;
                bundle.putString("url", murl);
                bundle.putString(Constant.TITLE, "桂花分");
                JumpUtils.jumptoNatvie(this, "webView", 0, bundle);

            } else if (isAuth.equals("2")) {
                Bundle bundle = new Bundle();
                bundle.putInt("intotype", 1);
                bundle.putString("choosetype", "ghf");
                JumpUtils.jumptoNatvie(this, "RealNameActivity", 0, bundle);
            }

        }
    }

    ProtocolsRes protocolsRes = new ProtocolsRes();
    ProtocolsRes protocolsWallet = new ProtocolsRes();
    ProtocolsRes protocolsFinance = new ProtocolsRes();
    ProtocolDialog protocolDialog;

    //查询到了协议之后  查询协议是否显示
    @Override
    public void getProtocolsSucc(ProtocolsRes protocolsRes) {
        if(protocolsRes.getUserAppAgreementDtos().size()==0){
            return;
        }
        if ("zhsz_app_zhuce".equals(protocolsRes.getSceneNo())) {
            this.protocolsRes = protocolsRes;
            mPresenter.showProtocols("zhsz_app_zhuce");//查询协议是否显示
        } else if ("shmjr_shq".equals(protocolsRes.getSceneNo())) { //获取金融协议
            protocolsFinance = protocolsRes;
            mPresenter.showProtocols("shmjr_shq"); //-->查询是否显示

        } else if ("hmqb_shq".equals(protocolsRes.getSceneNo())) {//获取钱包协议
            protocolsWallet = protocolsRes;
            //获取协议成功后显示
            mPresenter.showProtocols("hmqb_shq");//---->2 查询是否显示
        }

    }

    @Override
    public void getProtocolsFail() {

    }

    @Override
    public void showProtocolsSucc(ProtocolsShowRes protocolsShowRes) {
        //"1" 显示  "0" 不显示 zhsz_app_zhuce 注册协议  shmjr_shq 市民金融 hmqb_shq 惠民钱包
        String isFirst=protocolsShowRes.getIsFirst();
        if ("zhsz_app_zhuce".equals(protocolsShowRes.getSceneNo())) {
            currentOperation = "register";
            if ("1".equals(protocolsShowRes.getPopStatus())) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String versionCode = getProtocolVersion(protocolsRes);//获取协议的版本 并在方法里写入本地
                        protocolDialog = new ProtocolDialog(IMainActivity.this, protocolsRes);
                        protocolDialog.setCancelable(false);
                        //保证更新版本的弹窗在上面  用户协议的弹窗在下面
                        protocolDialog.getWindow().setType(WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW);
                        //重新登录之后都会新建这个对象 每个版本的协议是否点击过X都会写到本地object中
                        JSONObject jsonObject = ACache.get(DaggerApplication.getIns()).getAsJSONObject("protocol_list");
                        if (jsonObject == null) {
                            protocolDialog.show();
                            jsonObject = new JSONObject();
                        } else {
                            try {  //如果点击来X之后 这个值会是false 如果没有点击过就是null
                                Log.d("clark", jsonObject.getBoolean(versionCode) + "--");
                                if (jsonObject.get(versionCode) == null) {
                                    protocolDialog.show();
                                } else {
                                    //X过之后再token有效期不再显示
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        JSONObject finalJsonObject = jsonObject;
                        protocolDialog.setIProtocolDialog(new ProtocolDialog.IProtocolDialog() {
                            @Override
                            public void onclick() {
                                try {
                                    //将数据传到后台
                                    finalJsonObject.put(versionCode, true);
                                    //     * clientVersion : 客户端版本
                                    //     * operateSystem : 平台名称
                                    //     * sceneNo : s场景名称
                                    mPresenter.addUserAppAgreementRecord(versionName, "android", "zhsz_app_zhuce");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                ACache.get(DaggerApplication.getIns()).put("protocol_list", finalJsonObject);
                            }
                        });



                    }
                });
            }
        } else if ("hmqb_shq".equals(protocolsShowRes.getSceneNo())) {
            if (protocolsShowRes.getPopStatus().equals("1")) {
                //显示弹窗
                WalletAuthDialogNew walletAuthDialog = new WalletAuthDialogNew(this, "wallet", protocolsWallet,isFirst);
                walletAuthDialog.setCancelable(false);
                walletAuthDialog.setiWalletAuthDialog(new WalletAuthDialogNew.IWalletAuthDialogNew() {
                    @Override
                    public void onclick() {
                        mPresenter.addUserAppAgreementRecord(versionName, "android", "hmqb_shq");
                    }
                });
                walletAuthDialog.show();
            } else if (protocolsShowRes.getPopStatus().equals("0")) {
                //不显示弹窗
                mPresenter.verifybindWalletuser(mEvent.getData());
            }

        } else if ("shmjr_shq".equals(protocolsShowRes.getSceneNo())) {
            if (protocolsShowRes.getPopStatus().equals("1")) {
                //显示弹窗
                WalletAuthDialogNew walletAuthDialogNew = new WalletAuthDialogNew(this, "finance", protocolsFinance,isFirst);
                walletAuthDialogNew.show();
                walletAuthDialogNew.setCancelable(false);
                walletAuthDialogNew.setiWalletAuthDialog(new WalletAuthDialogNew.IWalletAuthDialogNew() {
                    @Override
                    public void onclick() {
                        mPresenter.addUserAppAgreementRecord(versionName, "android", "shmjr_shq");
                    }
                });
            } else if (protocolsShowRes.getPopStatus().equals("0")) {
                //不显示弹窗
                mPresenter.verifyBindNgUser(mEvent.getData());
            }
        }
    }

    @Override
    public void showProtocolsFail() {

    }

    @Override
    public void addUserAppAgreementRecordSucc(sz.szsmk.citizencard.model.network.bean.response.BaseBean baseBean) {
        Log.d("clark", "uploadDataSuccess");
        if (protocolDialog.isShowing()) {
            protocolDialog.dismiss();
        }

        if ("finance".equals(currentOperation)) {
            mPresenter.verifyBindNgUser(mEvent.getData());
        } else if ("wallet".equals(currentOperation)) {
            mPresenter.verifybindWalletuser(mEvent.getData());
        }

    }

    @Override
    public void addUserAppAgreementRecordFail() {
        Log.d("clark", "uploadDataFail");
    }

    @Override
    public void getUserComSucc(UserInfoRes userInfoRes) {
        userBundle = new Bundle();
        userBundle.putString("LV",userInfoRes.getIfL2()+"");
        userBundle.putString("phone",userInfoRes.getPhone());
        userBundle.putString("idCard",userInfoRes.getPaperNo()+"");
        userBundle.putString("reaName",userInfoRes.getUserName()+"");
        userBundle.putString("LV3",userInfoRes.getIfL3()+"");
        mFragments.get(0).setArguments(userBundle);
        mFragments.get(2).setArguments(userBundle);
        mFragments.get(3).setArguments(userBundle);
    }

    @Override
    public void onClick(View v) {

    }

    //根据返回的协议数据拼接处协议版本  并将此版本信息记录下来
    public String getProtocolVersion(ProtocolsRes protocolsRes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < protocolsRes.getUserAppAgreementDtos().size(); i++) {
            String versionStr = protocolsRes.getUserAppAgreementDtos().get(i).getVersionId() + "";
            if (i == protocolsRes.getUserAppAgreementDtos().size() - 1) {
                stringBuilder.append(versionStr);
            } else {
                stringBuilder.append(versionStr + "-");
            }
        }
        //记录当前的用户协议版本 闪屏进入程序的时候清空 重新获取协议，避免频繁请求接口造成服务器压力
        ACache.get(DaggerApplication.getIns()).put("protocolVersion", stringBuilder.toString());
        return stringBuilder.toString();

    }

}